<template>
  <div class="wrapper">
    <div class="head-wrapper">
      <router-link :to="{ path: '/user/import' }" @click="tiao(item)">
        <el-button type="primary">excel 导入</el-button></router-link
      >

      <el-button type="success" @click="state.visiable = true"
        >excel 导出</el-button
      >
    </div>
    <div class="table">
      <el-table :data="state.list" border style="width: 100%">
        <el-table-column type="index" label="#" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="mobile" label="联系方式" />
        <el-table-column prop="date" label="头像" align="center">
          <template #default="{ row }">
            <img :src="row.avatar" alt="" />
          </template>
        </el-table-column>
        <el-table-column prop="date" label="角色">
          <template #default="{ row: { role } }">
            <el-tag v-for="item in role" :key="item.id">{{
              item.title
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="开通时间">
          <template #default="{ row }">
            {{ dayjs(parseInt(row.openTime)).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center" width="230">
          <template #default>
            <el-button type="primary" size="small">编辑</el-button>
            <el-button type="info" size="small">角色</el-button>
            <el-button type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="state.queryModel.page"
        :page-sizes="[1, 2, 3, 4, 5, 6, 7, 8]"
        :page-size="state.queryModel.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.total"
      >
        <!-- :page-sizes="[1, 2, 3, 4]"-->
      </el-pagination>
    </div>
  </div>

  <el-dialog v-model="state.visiable" title="导出为 excel" width="30%">
    员工管理表
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visiable = false">取消</el-button>
        <el-button type="primary" @click="confirm">导出</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, toRefs, reactive, onMounted } from "vue";
import FileSaver from "file-saver";
import { daochu } from "@/http/user";
import { USER_RELATIONS } from "./Export2ExcelConstants";
import { useStore } from "vuex";

import { userlist } from "@/http/user.js";

import { ElMessageBox, ElMessage } from "element-plus";

const store = useStore();

const dayjs = require("dayjs"); //时间格式化

const state = reactive({
  visiable: false, //导出
  list: [], // 表格数据
  queryModel: {
    page: 1,
    size: 2,
  },
  total: 0,
});

let tiao = (item) => {
  console.log(item, "22");
  var obj = {
    title: "excel 导入",
    id: 200,
    path: "/user/import",
  };
  store.commit("addTags", obj);
};
/**
 * excel 导出点击事件
 */
let confirm = async () => {
  //所有员工列表
  let res = await daochu();
  let allUser = res.data.list;
  // 导入工具包
  let excel = await import("@/utils/Export2Excel");
  let data = formatJson(USER_RELATIONS, allUser);
  excel.export_json_to_excel({
    // excel 表头
    header: Object.keys(USER_RELATIONS),
    // excel 数据（二维数组结构）
    data,
    // 文件名称
    filename: "员工管理表",
    // 是否自动列宽
    autoWidth: true,
    // 文件类型
    bookType: "xlsx",
  });
  close();
};
close = () => {
  this.visiable = false;
};
// 该方法负责将数组转化成二维数组
const formatJson = (headers, rows) => {
  // 首先遍历数组
  // [{ username: '张三'},{},{}] => [[’张三'],[],[]]
  return rows.map((item) => {
    return Object.keys(headers).map((key) => {
      // 时间特殊处理
      if (headers[key] === "openTime") {
        return dateFormat(item[headers[key]]);
      }
      // 角色特殊处理
      if (headers[key] === "role") {
        const roles = item[headers[key]];
        return JSON.stringify(roles.map((role) => role.title));
      }
      return item[headers[key]];
    });
  });
};
//通过dayjs插件格式化时间
const dateFormat = (val, format = "YYYY-MM-DD") => {
  if (isNaN(val)) {
    return val;
  }
  val = parseInt(val);
  return dayjs(val).format(format);
};

/**
 * 获取数据
 */
let getuserList = async () => {
  const res = await userlist(state.queryModel);
  console.log(res);
  state.list = res.data.list;
  state.total = res.data.total;
  console.log(state.list);
};
let handleSizeChange = (v) => {
  console.log(v, "22");
  state.queryModel.size = v;
  getuserList();
};
let handleCurrentChange = (v) => {
  state.queryModel.page = v;
  getuserList();
};
onMounted(() => {
  getuserList();
});
</script>

<style lang="scss" scoped>
* {
  box-sizing: border-box;
  a {
    text-decoration: none;
  }
}
.wrapper {
  width: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .head-wrapper {
    width: 95%;
    height: 80px;
    padding: 20px;
    border: 1px solid rgb(216, 214, 214, 0.5);
    box-shadow: 2px 2px 2px 2px rgb(0 0 0 / 12%);
    display: flex;
    justify-content: flex-end;
    .el-button {
      margin-right: 10px;
    }
  }
  .table {
    margin-top: 20px;
    width: 95%;
    padding: 20px;
    box-shadow: 3px 3px 5px 5px rgb(0 0 0 / 12%);
    img {
      height: 60px;
      width: 60px;
      border-radius: 50%;
    }
  }
}
</style>